package com.developer.platform.infrastructure.security;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.developer.platform.domain.security.AuthorizationInfo;
import com.developer.platform.domain.service.IAuthorizingRealm;
import com.developer.platform.infrastructure.error.SecurityErrorType;
import java.util.Collection;
import java.util.List;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

/**
 * @author ：qiaoliang
 * @date ：2020-11-06
 */
@Component
public class SecurityAccessDecisionManager implements AccessDecisionManager {

    private final IAuthorizingRealm authorizingRealm;

    public SecurityAccessDecisionManager(IAuthorizingRealm authorizingRealm) {
        this.authorizingRealm = authorizingRealm;
    }

    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        if(CollUtil.isNotEmpty(collection)){
            for (ConfigAttribute configAttribute : collection) {
                List<AuthorizationInfo> authorities = authorizingRealm.doGetAuthorizationInfo(authentication);
                for (AuthorizationInfo authority : authorities) {
                    if(StrUtil.isNotBlank(authority.getMark())
                            && authority.getMark().equals(configAttribute.getAttribute())){
                        return;
                    }
                }
            }
            throw new AccessDeniedException(SecurityErrorType.PERMISSION_DENIED_ERROR.getMessage());
        }
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }

}
